package com.casic.modules.sys.api;


import com.casic.modules.sys.controller.AbstractController;
import com.casic.modules.sys.entity.SysAppversionEntity;
import com.casic.modules.sys.entity.VO.SysAppversionVO;
import com.casic.modules.sys.service.SysAppversionService;
import com.casic.modules.sys.service.SysEnclosureService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@Controller
@RequestMapping("/api/")
public class ApiVersionController extends AbstractController {

    @Autowired
    private SysAppversionService sysAppversionService;

    @Value("${spring.uploadFilePath}")
    private String  path;

    /**
     *  app版本下载
     * @param request
     * @param response
     */
    @RequestMapping(value = "downloadApk", method = RequestMethod.GET)
    public void downloadApk(HttpServletRequest request, HttpServletResponse response){
          try{
              SysAppversionVO sysAppversionVO=sysAppversionService.findVersion();
              //文件名
              String fileName =sysAppversionVO.getVersionName()+sysAppversionVO.getVersionCode()+".apk";
              //解决乱码
              String agent = request.getHeader("USER-AGENT");
              if (null != agent){
                  if (-1 != agent.indexOf("Firefox")) {//Firefox
                      fileName = "=?UTF-8?B?" + (new String(org.apache.commons.codec.binary.Base64.encodeBase64(fileName.getBytes("UTF-8"))))+ "?=";
                  }else if (-1 != agent.indexOf("Chrome")) {//Chrome
                      fileName = new String(fileName.getBytes(), "ISO8859-1");
                  } else {//IE7+
                      fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
                      fileName = StringUtils.replace(fileName, "+", "%20");//替换空格
                  }
              }
              // 设置response的编码方式
              response.setContentType("application/x-msdownload");
              // 设置附加文件名
              response.setHeader("Content-Disposition","attachment;filename="+fileName);
              File file=new File(path+sysAppversionVO.getFilePath());
              InputStream fis =new FileInputStream(file);
              OutputStream os = response.getOutputStream();
              byte[] b = new byte[2048];
              int length;
              while ((length = fis.read(b)) > 0) {
                  os.write(b, 0, length);
              }
              response.setContentLength((int)file.length());
              // 这里主要关闭。
              os.close();
              fis.close();
          }catch(Exception e){
              e.printStackTrace();
          }
    }
}
